package com.hnxxxy.oa.system.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hnxxxy.oa.system.VO.SysUserVO;
import com.hnxxxy.oa.enums.BizCodeEnum;
import com.hnxxxy.oa.exception.BizException;
import com.hnxxxy.oa.system.mapper.SysUserRoleMapper;
import com.hnxxxy.oa.system.model.SysUserDO;
import com.hnxxxy.oa.system.mapper.SysUserMapper;
import com.hnxxxy.oa.system.request.GeneralPageRequest;
import com.hnxxxy.oa.system.request.UserPageByUsernameRequest;
import com.hnxxxy.oa.system.request.UserRegisterRequest;
import com.hnxxxy.oa.system.service.SysUserRoleService;
import com.hnxxxy.oa.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 周石林
* @description 针对表【sys_user(用户)】的数据库操作Service实现
* @createDate 2022-05-03 15:33:13
*/
@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService{

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserRoleService sysUserRoleService;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT="oa";

    @Override
    public Integer userRegister(UserRegisterRequest userRegisterRequest) {

        //校验逻辑（省略）
        Integer roleId = userRegisterRequest.getRoleId();
        String username=userRegisterRequest.getUsername();
        String password=userRegisterRequest.getPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String email = userRegisterRequest.getEmail();
        Integer gender = userRegisterRequest.getGender();
        String actualName = userRegisterRequest.getActualName();

        //两次密码是否相同
        if(!password.equals(checkPassword)){
            throw new BizException(BizCodeEnum.PASSWORD_DIFFERENT);
        }

        //用户名是否唯一
        QueryWrapper<SysUserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Integer count = sysUserMapper.selectCount(queryWrapper);
        if(count>0){
            throw new BizException(BizCodeEnum.ACCOUNT_REPEAT);
        }

        // md5加盐加密: md5(md5(str) + md5(salt))
        String encryptedPassword = SaSecureUtil.md5BySalt(password, SALT);



        //插入数据
        SysUserDO sysUser = new SysUserDO();
        sysUser.setActualName(actualName);
        sysUser.setUsername(username);
        sysUser.setPassword(encryptedPassword);
        sysUser.setEmail(email);
        sysUser.setGender(gender);
        sysUserMapper.insert(sysUser);
        sysUserRoleService.addUserRole(sysUser.getId(),roleId);
        return sysUser.getId();
    }

    @Override
    public SysUserDO userLogin(String username, String password) {
        //校验逻辑（省略）

        //密码加密加盐
        String encryptedPassword=SaSecureUtil.md5BySalt(password,SALT);

        //查询用户名是否存在
        QueryWrapper<SysUserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",encryptedPassword);
        SysUserDO sysUser = sysUserMapper.selectOne(queryWrapper);
        if(sysUser==null) {
            log.info("user login fail,username cannot match userPassword");
            throw new BizException(BizCodeEnum.ACCOUNT_PWD_ERROR);
        }
        //返回用户脱敏对象
        return getSafetyUser(sysUser);
    }

    @Override
    public SysUserDO getSafetyUser(SysUserDO originUser) {
        if(originUser==null){
            return null;
        }
        SysUserDO sysUser = new SysUserDO();
        sysUser.setId(originUser.getId());
        sysUser.setActualName(originUser.getActualName());
        sysUser.setUsername(originUser.getUsername());
        sysUser.setEmail(originUser.getEmail());
        sysUser.setDepartId(originUser.getDepartId());
        sysUser.setGender(originUser.getGender());
        sysUser.setState(originUser.getState());
        sysUser.setCreateTime(originUser.getCreateTime());
        sysUser.setUpdateTime(originUser.getUpdateTime());
        return sysUser;
    }

    @Override
    public boolean deleteUser(int id) {
        SysUserDO sysUserDO = sysUserMapper.selectById(id);
        if (sysUserDO==null){
            throw new BizException(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
        int i = sysUserMapper.deleteById(id);
        return i==1;
    }

    @Override
    public List<SysUserDO> listUser() {
        return sysUserMapper.selectList(null);
    }

    @Override
    public Map<String, Object> pageListUsers(UserPageByUsernameRequest userPageByUsernameRequest) {
        Integer page = userPageByUsernameRequest.getPage();
        Integer size = userPageByUsernameRequest.getSize();
        String username = userPageByUsernameRequest.getUsername();
        //page为空设置默认值
        if (page==null || page<=0){
            page=1;
        }
        //size为空设置默认值
        if (size==null || size<=0){
            size=10;
        }
        Page<SysUserDO> pageInfo = new Page<>(page,size);
        QueryWrapper<SysUserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(username!=null,"username","%"+username+"%");
        Page<SysUserDO> sysUserDOPage = sysUserMapper.selectPage(pageInfo, queryWrapper);
        Map<String,Object> pageMap = new HashMap<>(3);
        pageMap.put("total_record",sysUserDOPage.getTotal());
        pageMap.put("total_page",sysUserDOPage.getPages());
        pageMap.put("current_data",sysUserDOPage.getRecords().stream()
                .map(obj->beanProocess(obj)).collect(Collectors.toList()));
        return pageMap;
    }

    @Override
    public SysUserDO selectUserById(int userId) {
        QueryWrapper<SysUserDO> sysUserDOQueryWrapper = new QueryWrapper<>();
        sysUserDOQueryWrapper.eq("id",userId);
        return sysUserMapper.selectOne(sysUserDOQueryWrapper);
    }

    @Override
    public boolean deleteUserByBatch(String ids) {
        String substring = ids.substring(1, ids.length() - 1);
        String[] split = substring.split(",");
        Integer[] splitInt=new Integer[split.length];
        for (int i=0;i<splitInt.length;i++){
            splitInt[i]=Integer.parseInt(split[i]);
        }
        List<Integer> collect = Arrays.stream(splitInt).collect(Collectors.toList());
        int i = sysUserMapper.deleteBatchIds(collect);
        return i>0;
    }

    private SysUserVO beanProocess(SysUserDO obj) {
        SysUserVO sysUserVO = new SysUserVO();
        BeanUtils.copyProperties(obj,sysUserVO);
        return sysUserVO;
    }
}